articles

Home / DeveloperSection / Articles / Connection Strings for MS Access

Connection Strings for MS Access

AVADHESH PATEL6546 26-Apr-2013

In this article I have described how to establish connection string in your application. Establishing a connection to an Access database in Visual Basic, C# and Java are given below.

Visual Basic 
Public Sub ConnectToAccess()
    Dim conn As New System.Data.OleDb.OleDbConnection()
    ' TODO: Modify the connection string and include any
    ' additional required properties for your database.
    conn.ConnectionString = & _
    "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & _
    "C:\Documents and Settings\username\My Documents\dbFile.mdb"
    Try
        conn.Open()
        ' Insert code to process data.
    Catch ex As Exception
        MessageBox.Show("Failed to connect to data source")
    Finally
        conn.Close()
    End Try
End Sub 
C#
 public void ConnectToAccess()
    {
        System.Data.OleDb.OleDbConnection conn = new
            System.Data.OleDb.OleDbConnection();
        // TODO: Modify the connection string and include any
        // additional required properties for your database.
        conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
            @"Data source= C:\Documents and Settings\username\" +
            @"My Documents\AccessFile.mdb";
        try
        {
            conn.Open();
            // Insert code to process data.
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to connect to data source");
        }
        finally
        {
            conn.Close();
        }
    } 
Java
 public void ConnectToAccess()
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String database =
              "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=myDB.mdb;";
            Connection conn = DriverManager.getConnection(database, "", "");
            Statement s = conn.createStatement();
            conn.close();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }



Updated 30-Nov-2017
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By